package com.spring.springboot.sys.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.spring.springboot.sys.core.constant.FieldConstants;
import com.spring.springboot.sys.core.model.UserInfo;
import com.spring.springboot.sys.util.UserInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author 宋义州
 */
@Slf4j
@Component
public class HeaderInterceptor implements HandlerInterceptor {

    /**
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) {
        String userInfoStr = request.getHeader(FieldConstants.USER_INFO_HEADER_NAME);
        if (StringUtils.isNotBlank(userInfoStr)) {
            try {
                UserInfoUtils.setUserInfo(JSONObject.parseObject(URLDecoder.decode(userInfoStr, "UTF-8"), UserInfo.class));
            } catch (UnsupportedEncodingException e) {
                log.error("解码失败", e);
            }
        }
        return true;
    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) {
        UserInfoUtils.remove();
    }

    /**
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) {

    }

}
